<template>
  <div class="sidebar">
    <el-menu
      class="sidebar-el-menu"
      :default-active="onRoutes"
      :collapse="collapse"
      background-color="#324157"
      text-color="#bfcbd9"
      active-text-color="#20a0ff"
      unique-opened
      router
    >
      <el-menu-item
        v-for="item in items"
        :index="item.index"
        :key="item.index"
      >
        <i :class="item.icon"></i>
        <span>{{ item.title }}</span>
      </el-menu-item>
    </el-menu>
  </div>
</template>

<script>
import bus from '../../components/common/bus';        // 统一用绝对路径，保证只有一个 bus 实例
import requests from '@/utils/request';

export default {
  name: 'Sidebar',
  data() {
    return {
      collapse: false,
      items: []
    };
  },
  computed: {
    onRoutes() {
      return this.$route.path.replace('/', '');
    },
    isSuperAdmin() {
      return this.$store.state.user && this.$store.state.user.isSuperAdmin;
    }
  },
  watch: {
    // 监听用户信息变化
    '$store.state.user': {
      handler(newUser, oldUser) {
        // 当用户信息发生变化时，重新获取菜单
        if (newUser && (!oldUser || newUser.isSuperAdmin !== oldUser.isSuperAdmin)) {
          this.getItems();
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    // 组件挂载后立刻拉一次（此时拿到的是当前已登录用户的 adminType）
    this.getItems();

    // 监听菜单刷新事件
    bus.$on('refresh-menu', () => {
      this.getItems();
    });

    // 仅保留 collapse 事件监听
    bus.$on('collapse', msg => {
      this.collapse = msg;
      bus.$emit('collapse-content', msg);
    });
  },
  beforeDestroy() {
    // 清理事件监听
    bus.$off('refresh-menu');
    bus.$off('collapse');
  },
  methods: {
    getItems() {
      // 先清空，防止旧数据残留
      this.items = [];
      
      // 确保用户信息存在
      if (!this.$store.state.user) {
        console.warn('用户信息不存在，无法获取菜单');
        return;
      }
      
      requests
        .get('/menuAdminType/getMenuByAdminType', {
          adminType: this.isSuperAdmin
        })
        .then(res => {
          this.items = res.map(({ menuId }) => ({
            icon: menuId.icon,
            index: menuId.path,
            title: menuId.title
          }));
        })
        .catch(err => {
          console.error('获取菜单失败：', err);
        });
    }
  }
};
</script>

<style scoped>
.sidebar {
  display: block;
  position: absolute;
  left: 0;
  top: 70px;
  bottom: 0;
  overflow-y: scroll;
}
.sidebar::-webkit-scrollbar {
  width: 0;
}
.sidebar-el-menu:not(.el-menu--collapse) {
  width: 250px;
}
.sidebar > ul {
  height: 100%;
}
</style>
